import axios from "axios";
import { createStore } from "vuex";
import { INCREMENT_N } from "./mutation-types";
const store = createStore({
  state() {
    return {
      counter: 0,
      name: "cc",
      height: 180,
      age: 18,
      bookList: [
        { name: "深入Vue", price: 204, count: 1 },
        { name: "React", price: 104, count: 2 },
        { name: "深入Node", price: 235, count: 4 },
        { name: "深入Php", price: 134, count: 5 },
        { name: "深入Java", price: 220, count: 3 },
      ],
      bookDiscount: 1,
      banners: [],
    };
  },
  getters: {
    totalPrice(state, getters) {
      let total = 0;
      for (const book of state.bookList) {
        total += book.price * book.count;
      }
      return total * getters.currentDistant;
    },
    currentDistant(state) {
      return state.bookDiscount * 0.9;
    },
    totalPriceCountGreaterN(state, getters) {
      return function (n) {
        let total = 0;
        for (const book of state.bookList) {
          if (book.count > n) {
            total += book.price * book.count;
          }
        }
        return total * getters.currentDistant;
      };
    },
    nameInfo(state) {
      return `name:${state.name}`;
    },
    ageInfo(state) {
      return `age:${state.age}`;
    },
    heightInfo(state) {
      return `height:${state.height}`;
    },
  },
  mutations: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
    // 10 -> payload
    // {n: 10, name: "why", age: 18} -> payload
    [INCREMENT_N](state, payload) {
      console.log(payload);
      state.counter += payload.n;
    },
    addBannerData(state, payload) {
      state.banners = payload;
    },
  },
  actions: {
    // 放函数
    // 1.参数问题
    incrementAction(context, payload) {
      console.log(payload);
      setTimeout(() => {
        context.commit("increment");
      }, 1000);
    },
    // 2.context的其他属性
    decrementAction({
      commit,
      dispatch,
      state,
      rootState,
      getters,
      rootGetters,
    }) {
      commit("decrement");
    },
    getHomeMultidata(context) {
      return new Promise((resolve, reject) => {
        axios
          .get("http://123.207.32.32:8000/home/multidata")
          .then((res) => {
            context.commit("addBannerData", res.data.data.banner.list);
            resolve({ name: "coderwhy", age: 18 });
          })
          .catch((err) => {
            reject(err);
          });
      });
    },
  },
});

export default store;
